package com.example.net1;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.Random;

import com.example.net1.Message;

public class MyServer {
	
	public static final int PORT = 9999;
	public static final String clientReq=  "Hello message";
	public static final String bankInfo = "Bank Information";

	static Message process(Message message) throws UnsupportedEncodingException{
		Message serverMessage = null;
		if(message.getTag().equals(clientReq)){
			 serverMessage = new Message("TWIX 20$");			
		 }
		 if(message.getTag().equals(bankInfo)){			 
			 serverMessage = new Message(Math.abs(new Random().nextInt())+"");			
		 }
		 return serverMessage;		
	}	
	
	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 */
	public static void main(String[] args) throws ClassNotFoundException {
		// TODO Auto-generated method stub

		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream is = null;
		OutputStream os = null;

		try {
			serverSocket = new ServerSocket(PORT);
			System.out.println("Listening :"+PORT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		while(true){
			try {
				socket = serverSocket.accept();
				is =  socket.getInputStream();
				os =  socket.getOutputStream();
				System.out.println("ip: " + socket.getInetAddress());	
				ObjectOutputStream oos = new ObjectOutputStream(os);  	
				ObjectInputStream ois = new ObjectInputStream(is);  							
		        while(true){
					Message message =  (Message)ois.readObject(); 
					System.out.println("Client Message: "+message.getTag());
					Message serverMessage = process(message);						
		            oos.writeObject(serverMessage);	
		            oos.flush();
		        }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally{
				if( socket!= null){
					try {
						socket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				if( is!= null){
					try {
						is.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if( os!= null){
					try {
						os.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}